<!--员工管理-->
<template>

  <!-- 搜索卡片 -->
  <el-card shadow="hover" style="margin: 20px;min-height: 70px">
    <el-form :inline="true" style="padding-top:10px;">
      <el-row :gutter="10">
        <!-- 现有的表单项 -->
        <el-col :span="6">
          <el-form-item label="员工姓名" style="width: 90%;">
            <el-input placeholder="请输入姓名" v-model="searchFrom.username"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="员工工号" style="width: 90%;">
            <el-input placeholder="请输入工号" v-model="searchFrom.jobNumber"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="员工状态" style="width: 90%;">
            <el-select placeholder="请选择员工状态" v-model="searchFrom.status">
              <el-option label="启用" value="1"/>
              <el-option label="禁用" value="0"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item style="margin-left: 30px;">
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="search">查询</el-button>
            <el-button link
                       @click="toggleCollapse">
              {{ isCollapsed ? '收起' : '展开' }}
              <el-icon :size="16" :class="{ 'rotate-icon': isCollapsed }">
                <CaretRight/>
              </el-icon>
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 折叠 -->
      <transition name="fade">
        <div v-if="isCollapsed" style="margin-top: 10px;">
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="员工职位" style="width: 90%;">
                <el-select placeholder="请选择员工职位" v-model="searchFrom.role">
                  <el-option v-for="item in roleArr" :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="员工电话" style="width: 90%;">
                <el-input placeholder="请输入电话" v-model="searchFrom.phone"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </transition>
    </el-form>
  </el-card>

  <el-card style="margin: 20px;height: 63vh">
    <div style="margin:10px 0 40px 10px;">
      员工列表
      <div style="float: right">
        <el-button type="success" @click="addEmployee">添加员工</el-button>
        <el-button type="primary" @click="selectAll">全选</el-button>
        <el-button type="primary" @click="clearSelection">取消全选</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
        <el-button type="primary" @click="exportEmployees">导出员工</el-button>
      </div>
    </div>

    <el-table ref="multipleTableRef"
              @selection-change="handleSelectionChange"
              :data="paginatedData" stripe
              style="margin-top: 20px;height: 360px">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column type="index" label="编号" width="80" align="center"/>
      <el-table-column label="员工姓名" prop="username" align="center"/>
      <el-table-column label="员工工号" prop="jobNumber" align="center"/>
      <el-table-column label="手机号" prop="phone" width="110" align="center"/>
      <el-table-column label="员工职位" prop="role" align="center"
                       :formatter="roleTypeFormatter"/>
      <el-table-column label="员工状态" prop="status" align="center">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              active-value="1"
              inactive-value="0"
              @change="updateStatus(scope.row.id, scope.row.status)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280px" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="resetPassword(scope.row.id)">密码重置</el-button>
          <el-button link type="primary" @click="editEmployee(scope.row.id)">编辑</el-button>
          <el-button link type="primary" @click="deleteEmployee(scope.row.id)"
                     :disabled="getEmployeeId === scope.row.id">删除
          </el-button>
          <el-button link type="primary" @click="findAll(scope.row.id)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>


      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="tableData.length"
          @current-change="handlePageChange"
          style="margin-top:20px;margin-left:  35%"
      />


  </el-card>

  <el-dialog :title="employeeTitle"
             v-model="employeeVisible"
             style=" position: absolute;
                       top: 30%;
                       left: 40%;
                       transform: translate(-30%, -40%);
                       width: 800px;
                       padding: 40px;"
             :before-close="cancel"
  >
    <el-form ref="form" label-width="80px" label-position="top">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="员工姓名">
            <el-input type="text" placeholder="请输入员工姓名"
                      v-model="saveFrom.username"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="员工职位">
            <el-select placeholder="请选择员工职位" v-model="saveFrom.role">
              <el-option v-for="item in roleArr" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="手机号">
            <el-input type="text" placeholder="请输入手机号" v-model="saveFrom.phone"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号">
            <el-input type="text" placeholder="请输入身份证号" v-model="saveFrom.idNumber"
                      :disabled="employeeTitle==='编辑信息'"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="员工状态">
            <el-radio-group v-model="saveFrom.status">
              <el-radio label="启用" value="1"/>
              <el-radio label="禁用" value="0"/>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <template #footer>
      <el-button type="danger" @click="handleClose">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </template>
  </el-dialog>


  <el-dialog v-model="particularsVisible" style="width: 800px;
                                                 position: absolute;
                                                 top: 30%;left: 40%;
                                                 transform: translate(-20%, -50%);
                                                 padding: 20px">
    <el-descriptions title="详情信息"
                     border
                     label-width="80px">
      <el-descriptions-item
          :rowspan="2"
          :width="140"
          label="图片"
          align="center"
      >
        <el-image
            v-if="particularsData && particularsData.avatar"
            style="width: 100px; height: 100px"
            :src="BASE_URL + particularsData.avatar"
            alt="User Avatar"
        />
      </el-descriptions-item>
      <el-descriptions-item label="员工姓名" align="center">{{ particularsData.username }}</el-descriptions-item>
      <el-descriptions-item label="员工性别" align="center">
        <template #default="scope">
          <span v-if="particularsData.gender  == 1">男</span>
          <span v-else-if="particularsData.gender  == 2">女</span>
        </template>
      </el-descriptions-item>
      <el-descriptions-item label="员工电话" align="center">{{ particularsData.phone }}</el-descriptions-item>
      <el-descriptions-item label="员工职位" align="center">
        {{ roleTypeFormatter(particularsData, null, particularsData.role) }}
      </el-descriptions-item>
      <el-descriptions-item label="员工工号" align="center">{{ particularsData.jobNumber }}</el-descriptions-item>
      <el-descriptions-item label="身份证号" align="center">{{ particularsData.idNumber }}</el-descriptions-item>
      <el-descriptions-item label="出生日期" align="center">{{ particularsData.birthday }}</el-descriptions-item>
      <el-descriptions-item label="入职时间" align="center">{{ particularsData.createTime }}</el-descriptions-item>
      <el-descriptions-item label="员工状态" align="center">
        <template #default="scope">
          <span v-if="particularsData.status  == 1">激活</span>
          <span v-else-if="particularsData.status  == 0">失效</span>
        </template>
      </el-descriptions-item>
      <el-descriptions-item label="员工邮箱" align="center">{{ particularsData.email }}</el-descriptions-item>
      <el-descriptions-item label="家庭地址">{{ particularsData.address }}</el-descriptions-item>
    </el-descriptions>

  </el-dialog>


</template>

<script setup>
import {computed, onMounted, ref} from 'vue';
import {CaretRight} from "@element-plus/icons-vue";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import qs from 'qs';
import * as XLSX from "xlsx";
import selectedRows from "core-js/internals/array-iteration";

const isCollapsed = ref(false);

const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};
const roleArr = ref([]);
onMounted(() => {
  loadDictOptions(roleArr, 'role');
});
const roleTypeFormatter = (row, column, cellValue, index) => {
  if (!roleArr.value) {
    return cellValue;
  }
  for (let item of roleArr.value) {
    if (item.value === cellValue) {
      cellValue = item.label;
    }
  }
  return cellValue;
}
const tableData = ref([]);
const currentPage = ref(1);// 默认显示页码
const pageSize = ref(6); // 每页显示6条

// 计算当前页面的数据
const paginatedData = computed(() => {
  const offset = (currentPage.value - 1) * pageSize.value;
  return tableData.value.slice(offset, offset + pageSize.value);
});

// 分页变化时触发
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};

const searchFrom = ref({
  username: '',
  jobNumber: '',
  status: '',
  phone: '',
  role: '',
});
const search = () => {
  let data = qs.stringify(searchFrom.value);
  axios.get(BASE_URL + '/v1/employee/select?' + data)
      .then((response) => {
        if (response.data.code === 2000) {
          tableData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
};
onMounted(() => {
  search();
})
const resetSearch = () => {
  searchFrom.value = {};
  search();
}
const employeeVisible = ref(false);
const employeeTitle = ref('添加员工');
const saveFrom = ref({
  username: '',
  phone: '',
  role: '',
  status: '1',
  idNumber: '',
});
const cleanAll = () => {
  saveFrom.value = {
    username: '',
    phone: '',
    role: '',
    status: '1',
    idNumber: '',
  };
};


const addEmployee = () => {
  employeeVisible.value = true;
  employeeTitle.value = '添加员工';
}

const save = () => {
  if (saveFrom.value.username === '' || !saveFrom.value.username) {
    errorInfo('请输入员工姓名');
    return;
  }
  if (saveFrom.value.role === '' || !saveFrom.value.role) {
    errorInfo('请选择员工职位');
    return;
  }
  if (saveFrom.value.phone === '' || !saveFrom.value.phone) {
    errorInfo('请输入员工手机号');
    return;
  }
  if (saveFrom.value.phone.length !== 11) {
    errorInfo('请输入正确的11位手机号');
    return;
  }
  if (saveFrom.value.idNumber === '' || !saveFrom.value.idNumber) {
    errorInfo('请输入员工身份证号');
    return;
  }
  const idNumberRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dxX]$/;
  if (!idNumberRegex.test(saveFrom.value.idNumber)) {
    errorInfo('请输入正确的18位身份证号格式');
    return;
  }
  if (saveFrom.value.status === '' || !saveFrom.value.status) {
    errorInfo('请选择员工状态');
    return;
  }

  let data = qs.stringify(saveFrom.value)
  axios.post(BASE_URL + '/v1/employee/save', data)
      .then((response) => {
        if (response.data.code === 2000) {
          OKInfo('保存成功!');
          cleanAll();
          employeeVisible.value = false;
          search();
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
};
const handleClose = () => {
  ElMessageBox.confirm('是否取消保存？', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    employeeVisible.value = false;
    cleanAll();
    Info('已取消保存');
  }).catch(() => {
    //取消没有操作
  });
};
const particularsVisible = ref(false);
const particularsData = ref({
  avatar: '',
  username: '',
  jobNumber: '',
  idnumber: '',
  birthday: '',
  phone: '',
  role: '',
  email: '',
  createTime: '',
  address: '',
  gender: '',
  status: '',
});
const findAll = (id) => {
  particularsVisible.value = true;
  axios.get(BASE_URL + '/v1/employee/select?id=' + id)
      .then((response) => {
        if (response.data.code === 2000) {
          particularsData.value = response.data.data[0];
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}

const editEmployee = (id) => {
  employeeVisible.value = true;
  employeeTitle.value = '编辑信息';
  axios.get(BASE_URL + '/v1/employee/select?id=' + id)
      .then((response) => {
        if (response.data.code === 2000) {
          saveFrom.value = response.data.data[0];
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })

}
const updateStatus = (id, status) => {
  axios.put(BASE_URL + '/v1/employee/update/status/' + id + '/' + status)
      .then((response) => {
        if (response.data.code === 2000) {
          OKInfo('状态修改成功!')
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          })
        }
      })
}
const resetPassword = (id) => {
  ElMessageBox.confirm('确定重置该员工密码吗？', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    axios.put(BASE_URL + '/v1/employee/update/password/' + id)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('密码重置成功!');
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
            })
          }
        })
  }).catch(() => {
    Info('已取消重置')
  });
}
const getEmployeeId = getEmployee().id;

// 删除员工的方法
const deleteEmployee = (id) => {
  ElMessageBox.confirm('确定删除该员工吗？', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    return ElMessageBox.prompt('请输入您的工号以确认删除操作:', '工号验证', {
      customClass: 'custom-message-box',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      draggable: true,
    });
  }).then(({value}) => {
    // 手动验证输入的工号格式（假设工号是数字）
    const inputPattern = /^\d+$/;
    if (!inputPattern.test(value)) {
      errorInfo('工号格式不正确')
      return Promise.reject(); // 拒绝继续执行
    }
    const getEmployeeJobNumber = getEmployee().jobNumber;
    // 验证输入的工号是否匹配当前用户的工号
    if (value !== getEmployeeJobNumber) {
      console.log('value:' + value)
      console.log('getEmployeeJobNumber:' + getEmployeeJobNumber)
      errorInfo('工号验证失败，请重新输入正确的工号。')
      return Promise.reject(); // 拒绝继续执行
    }

    return axios.delete(BASE_URL + '/v1/employee/delete/' + id);
  }).then((response) => {
    if (response.data.code === 2000) {
      OKInfo('删除成功!');
      search();
    } else {
      ElMessage({
        message: response.data.msg,
        type: 'error',
        showClose: true,
        center: true,
      });
    }
  }).catch((action) => {
    if (action !== 'cancel') {
      Info('已取消删除');
    }
  });
};

const exportEmployees = async () => {
  search();
  try {
    // 定义固定的表头
    const headers = [
      'id', 'username', 'password', 'jobNumber', 'idNumber',
      'birthday', 'gender', 'phone', 'address', 'role',
      'email', 'avatar', 'status', 'createTime', 'updateTime'
    ];

    // 将 JSON 数据转换为二维数组
    const data = tableData.value.map(employee => headers.map(header => employee[header]));

    // 检查数据有效性
    if (!data.length || !data.every(row => Array.isArray(row) && row.length === headers.length)) {
      errorInfo('导出失败：数据为空');
      return;
    }

    // 直接在数据前插入表头
    data.unshift(headers);

    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(data);
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    // 动态生成文件名
    // 获取当前日期并格式化为 YYYY_MM_DD 格式
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
    const day = String(now.getDate()).padStart(2, '0');

    const formattedDate = `${year}_${month}_${day}`;
    const fileName = `employees_export_${formattedDate}.xlsx`;

    // 导出Excel文件
    XLSX.writeFile(wb, fileName);

    // 提示用户导出成功
    OKInfo('导出成功');
  } catch (error) {
    errorInfo('导出失败，请检查控制台日志');
  }
};
// 表格引用
const multipleTableRef = ref(null);

const selectedIdsValue = ref([]);
// 监听选择变化
const handleSelectionChange = (selection) => {
  // 更新当前选中的行
  selectedRows.value = selection;
  // 提取所有选中行的ID
  selectedIdsValue.value = selection.map(row => row.id);
};
// 全选方法
const selectAll = () => {
  multipleTableRef.value.toggleAllSelection();
};

// 取消全选的方法
const clearSelection = () => {
  multipleTableRef.value.clearSelection();
};

// 批量删除的方法
const batchDelete = () => {
  if (selectedIdsValue.value.length === 0) {
    Info('请选择要删除的行');
    return;
  }

  if (selectedIdsValue.value.includes(getEmployee().id)) {
    errorInfo('不能删除自己,请重新选择');
    clearSelection();
    return;
  }

  let data = selectedIdsValue.value.join(',');
  ElMessageBox.confirm('确定删除选中的员工吗？', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    return ElMessageBox.prompt('请输入您的工号以确认删除操作:', '工号验证', {
      customClass: 'custom-message-box',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      draggable: true,
    });
  }).then(({value}) => {
    // 手动验证输入的工号格式（假设工号是数字）
    const inputPattern = /^\d+$/;
    if (!inputPattern.test(value)) {
      errorInfo('工号格式不正确')
      return Promise.reject(); // 拒绝继续执行
    }
    const getEmployeeJobNumber = getEmployee().jobNumber;
    // 验证输入的工号是否匹配当前用户的工号
    if (value !== getEmployeeJobNumber) {
      console.log('value:' + value)
      console.log('getEmployeeJobNumber:' + getEmployeeJobNumber)
      errorInfo('工号验证失败，请重新输入正确的工号。')
      return Promise.reject(); // 拒绝继续执行
    }

    return axios.delete(BASE_URL + '/v1/employee/delete/batch/' + data);
  }).then(() => {
    axios.delete(BASE_URL + '/v1/employee/delete/batch/' + data)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('删除成功!')
            search();
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            })
          }
        })
  }).catch(() => {
    Info('已取消删除')
  });

};

</script>

<style scoped>
.rotate-icon {
  transform: rotate(90deg);
  transition: transform .3s;
}
</style>